package com.sgcc.activiti.controller;

//import com.alibaba.fastjson.JSONObject;

import com.sgcc.activiti.domain.OContentAd;
import com.sgcc.activiti.domain.OContentAdSchema;
import com.sgcc.activiti.domain.OInterfaceIndex;
import com.sgcc.activiti.service.IOContentAdSchemaService;
import com.sgcc.activiti.service.IOContentAdService;
import com.sgcc.activiti.service.IOInterfaceIndexService;
import com.sgcc.activiti.service.IProcessService;
import com.sgcc.common.core.domain.R;
import com.sgcc.common.core.utils.DateUtils;
import com.sgcc.common.core.utils.FastJsonUtil;
import com.sgcc.common.core.utils.HttpClientUtil;
import com.sgcc.common.core.utils.StringUtils;
import com.sgcc.common.core.utils.poi.ExcelUtil;
import com.sgcc.common.core.web.controller.BaseController;
import com.sgcc.common.core.web.domain.AjaxResult;
import com.sgcc.common.core.web.page.TableDataInfo;
import com.sgcc.common.log.annotation.Log;
import com.sgcc.common.log.enums.BusinessType;
import com.sgcc.common.security.annotation.PreAuthorize;
import com.sgcc.common.security.service.TokenService;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 广告管理维护方案Controller
 *
 * @author sgcc
 * @date 2021-04-07
 */
@RestController
@RequestMapping("/OContentAdSchema")
public class OContentAdSchemaController extends BaseController {
    @Autowired
    private IOContentAdSchemaService oContentAdSchemaService;
    @Autowired
    private IProcessService processService;
    @Autowired
    private IOInterfaceIndexService interfaceIndexService;
    @Autowired
    private IOContentAdService oContentAdService;
    @Autowired
    private TokenService tokenService;


    @Log(title = "提交资讯流程", businessType = BusinessType.UPDATE)
    @PostMapping("/submitApply/{id}")
    @ResponseBody
    public AjaxResult submitApply(@PathVariable String id) {
        try {
            OContentAdSchema obj = oContentAdSchemaService.selectOContentAdSchemaById(id);
            processService.submitApply(obj, "content_ad");
            oContentAdSchemaService.updateOContentAdSchema(obj);
        } catch (Exception e) {
            e.printStackTrace();
            return error("提交申请出错：" + e.getMessage());
        }
        return success();
    }

    /**
     * 查询广告管理维护方案列表
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAdSchema:list")
    @GetMapping("/list")
    public TableDataInfo list(OContentAdSchema oContentAdSchema) {
        startPage();
        List<OContentAdSchema> list = oContentAdSchemaService.selectOContentAdSchemaList(oContentAdSchema);
        return getDataTable(list);
    }


    /**
     * 查询广告管理维护方案列表
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAdSchema:list")
    @GetMapping("/listProcess")
    public TableDataInfo listProcess(OContentAdSchema oContentAdSchema) {
        startPage();
        if("f3".equals(oContentAdSchema.getProcessId())){
            oContentAdSchema.setSpareThree("true");
        }
        List<OContentAdSchema> list = oContentAdSchemaService.selectOContentAdSchemaListProcess(oContentAdSchema);
        return getDataTable(list);
    }

    //@PreAuthorize(hasPermi = "activiti:OContentAdSchema:list")
    @GetMapping("/listSubmitist")
    public TableDataInfo listSubmitist(OContentAdSchema oContentAdSchema) {
        startPage();
        List<OContentAdSchema> list = oContentAdSchemaService.selectOContentAdSchemaListSubmitist(oContentAdSchema);
        return getDataTable(list);
    }


    /**
     * 导出广告管理维护方案列表
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAdSchema:export")
    @Log(title = "广告管理维护方案", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OContentAdSchema oContentAdSchema) throws IOException {
        List<OContentAdSchema> list = oContentAdSchemaService.selectOContentAdSchemaList(oContentAdSchema);
        ExcelUtil<OContentAdSchema> util = new ExcelUtil<OContentAdSchema>(OContentAdSchema.class);
        util.exportExcel(response, list, "OContentAdSchema");
    }

    /**
     * 获取广告管理维护方案详细信息
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAdSchema:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(oContentAdSchemaService.selectOContentAdSchemaById(id));
    }

    /**
     * 新增广告管理维护方案
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAdSchema:add")
    @Log(title = "广告管理维护方案", businessType = BusinessType.INSERT)
    @PostMapping(value = "/addOContentAdSchemaSave")
    public AjaxResult addOContentAdSchemaSave(@RequestBody OContentAdSchema oContentAdSchema) {
        if (null != oContentAdSchema.getNewId()) {
            Integer num = oContentAdSchemaService.selectOContentAdByNewId(oContentAdSchema.getNewId());
            if (num > 0) {
                return AjaxResult.error("已在进行流程~");
            }
        }

        return toAjax(oContentAdSchemaService.insertOContentAdSchema(oContentAdSchema));
    }

    //@PreAuthorize(hasPermi = "activiti:OContentAdSchema:add")
    @Log(title = "广告管理维护方案", businessType = BusinessType.INSERT)
    @PostMapping(value = "/addOContentAdSchemaSubmit")
    public AjaxResult addOContentAdSchemaSubmit(@RequestBody OContentAdSchema oContentAdSchema) {
        Integer num = oContentAdSchemaService.selectOContentAdByNewId(oContentAdSchema.getNewId());
        if (num > 0) {
            return AjaxResult.error("已在进行流程~");
        }


        Integer i = oContentAdSchemaService.insertOContentAdSchema(oContentAdSchema);

        OContentAdSchema OContentAdSchema = oContentAdSchemaService.selectOContentAdSchemaById(oContentAdSchema.getId());
        try {
            processService.richProcessField(OContentAdSchema);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String taskId = OContentAdSchema.getTaskId();
        String instanceId = OContentAdSchema.getInstanceId();
        JSONObject obj = new JSONObject();
        obj.put("pass", true);
        obj.put("comment", "同意");
        obj.put("formData", OContentAdSchema);
        String variables = obj.toString();


        AjaxResult result = processService.complete(taskId, instanceId, variables);
        return toAjax(i);
    }

    /**
     * 修改广告管理维护方案
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAdSchema:edit")
    @Log(title = "广告管理维护方案", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OContentAdSchema oContentAdSchema) {
        return toAjax(oContentAdSchemaService.updateOContentAdSchema(oContentAdSchema));
    }

    /**
     * 删除广告管理维护方案
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAdSchema:remove")
    @Log(title = "广告管理维护方案", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(oContentAdSchemaService.deleteOContentAdSchemaByIds(ids));
    }

    /**
     * 广告审核
     */
    @ResponseBody
    @RequestMapping(value = "audit", method = RequestMethod.POST)
    @ApiOperation(notes = "audit", httpMethod = "POST", value = "广告审核")
    @Log(title = "广告审核", businessType = BusinessType.OTHER)
    public AjaxResult audit(OContentAdSchema oContentAdSchemaDto, Model model, String auditType) throws Exception {
        String id = oContentAdSchemaDto.getId();
        if (StringUtils.isBlank(id)) {
            return AjaxResult.error(400, "缺少参数");
        }
        OContentAdSchema oContentAdSchema = oContentAdSchemaService.selectOContentAdSchemaById(id);
        long time = System.currentTimeMillis();
        Date date1 = new Date(time);
//		OContentAdSchema oContentAdSchema = new OContentAdSchema();
//		BeanUtils.copyProperties(oContentAdSchemaDto, oContentAdSchema);
        //维护类型，操作类型：serviceType 01	新增 02	变更 03	下架
        String serviceType = oContentAdSchema.getServiceType();
        String procInsId = oContentAdSchema.getProcInsId();
        String newId = oContentAdSchema.getNewId();
        String spareOne = oContentAdSchema.getSpareOne();
        if ("0".equals(auditType)) {
            //auditType 0,审核不通过
            //审核不通过
            if ("01".equals(serviceType) || "02".equals(serviceType) || "03".equals(serviceType)) {
                //新增审核
                //编辑表单
                // 当前环节，包括流程的环节，有结束、终止等
                oContentAdSchema.setActName("广告维护");
                //流采用标准编码 flowType 01待提交 02待审核 03待发布 04发布失败 05结束 06失败结束
                oContentAdSchema.setFlowType("01");
                oContentAdSchema.setSpareFive(DateUtils.convertToString(date1, DateUtils.YYYY_MM_DD_HH_MM_SS));
                oContentAdSchemaService.insertOContentAdSchema(oContentAdSchema);
            }
        } else if ("1".equals(auditType)) {
            //auditType 1,审核通过
            //审核通过
            if ("01".equals(serviceType) || "02".equals(serviceType)) {
                //新增审核
                //编辑表单
                // 当前环节，包括流程的环节，有结束、终止等
                oContentAdSchema.setActName("广告发布");
                //流采用标准编码 flowType 01待提交 02待审核 03待发布 04发布失败 05结束 06失败结束
                oContentAdSchema.setFlowType("03");
                oContentAdSchema.setSpareFive(DateUtils.convertToString(date1, DateUtils.YYYY_MM_DD_HH_MM_SS));
                oContentAdSchemaService.insertOContentAdSchema(oContentAdSchema);

            } else if ("03".equals(serviceType)) {
                logger.info("广告下架执行审核成功");
                //下架审核
                Integer resultCode = 0;
                String message = "";
                String callBackResult = "";
                String rpcInterface = "test";
                /**
                 * 调用远程接口，下架该广告
                 */
//                String rpcInterface = DictUtils.getDictValue("统一业务接口", "rpcInterface", "test");
                OInterfaceIndex oInterfaceIndex = interfaceIndexService.selectAddressbycode("0101204");
                if (null != oInterfaceIndex && null != oInterfaceIndex.getInterfaceAdress()) {
                    rpcInterface = oInterfaceIndex.getInterfaceAdress();
                }else{
                    return AjaxResult.error("0101204接口未配置");
                }
                if ("test".equals(rpcInterface)) {
                    resultCode = 1;
                } else {
                    logger.info("进入广告下请求接口2");
                    String params = "";
                    //构建参数
                    /**
                     * {
                     *  "serviceCode": "0101204",
                     *  "source": "SGAPP",
                     *  "target": "35101",
                     *   "data":{
                     *    "serialNum":"add96eb0aw5f04ewww32aba67cec3",
                     *    "serviceType":"asc2ed",
                     *    "platformId":"330000",
                     *    "adId":"1cbceb75dc84400ba298450adb053442",
                     *    "releaseScope":"330000"
                     *   }
                     * }
                     */
                    Map paramsData = new HashMap();
                    paramsData.put("serialNum", oContentAdSchema.getId());
                    paramsData.put("serviceType", "03");
                    paramsData.put("platformId", "350000");
                    paramsData.put("adId", oContentAdSchema.getNewId());
                    paramsData.put("releaseScope", "350000");
                    /*CommonParm commonParm = new CommonParm();
                    commonParm.setTarget("35101");
                    commonParm.setSource("SGAPP");
                    commonParm.setServiceCode("0101204");
                    commonParm.setData(paramsData);*/

                    Map map = new HashMap();
                    map.put("serviceCode", "0101204");
                    map.put("source", "SGAPP");
                    map.put("target", "35101");
                    map.put("data", paramsData);
                    params = FastJsonUtil.toJSONString(map);
                    R<String> rpcResultStr = HttpClientUtil.sendJsonStr(rpcInterface, params);
                    //解析返回值
                    if (rpcResultStr.getCode() != 200) {
                        return AjaxResult.error(oInterfaceIndex.getInterfaceAdress() + "接口调用失败！" + rpcResultStr.getCode());
                    }
                    R r = FastJsonUtil.toBean(rpcResultStr.getData(), R.class);
                    resultCode = r.getCode();
                    message = r.getMsg();
                    if ("1".equals(resultCode) || 1 == resultCode) {
                        JSONObject data = (JSONObject) r.getData();
                        /**
                         * 判断回调返回值
                         */
                        OContentAd condition = new OContentAd();
                        condition.setNewId(oContentAdSchema.getNewId());
                        List<OContentAd> list = oContentAdService.selectOContentAdList(condition);
                        OContentAd callBackAd = list.get(0);
                        callBackResult = callBackAd.getSpareFive();
                        if (StringUtils.isNotBlank(callBackResult)) {
                            String[] split = callBackResult.split(":");
                            resultCode = Integer.valueOf(split[0]);
                            message = split[1];
                        } else {
                            long callBackFlag = 0;
                            long callBackTimes = Long.valueOf(10);
                            while (callBackFlag < callBackTimes) {
                                callBackFlag++;
                                OContentAd condition2 = new OContentAd();
                                condition2.setNewId(oContentAdSchema.getNewId());
                                List<OContentAd> list2 = oContentAdService.selectOContentAdList(condition2);
                                OContentAd callBackAd2 = list2.get(0);
                                callBackResult = callBackAd2.getSpareFive();
                                if (StringUtils.isNotBlank(callBackResult)) {
                                    String[] split2 = callBackResult.split(":");
                                    resultCode = Integer.valueOf(split2[0]);
                                    message = split2[1];
                                    callBackFlag = callBackTimes;
                                } else {
                                    Thread.sleep(1000L);
                                }
                            }
                        }
                        if (StringUtils.isBlank(callBackResult)) {
                            resultCode = 0;
                            message = "远程系统没有调用回调接口";
                        }
                    }
                }

                /**
                 * 业务流程
                 */
                if ("1".equals(resultCode) || 1 == resultCode) {
                    //调用远程接口成功，并成功下架
                    //编辑表单
                    // 当前环节，包括流程的环节，有结束、终止等
                    oContentAdSchema.setActName("结束");
                    //流采用标准编码 flowType 01待提交 02待审核 03待发布 04发布失败 05结束 06失败结束
                    oContentAdSchema.setFlowType("05");
                    oContentAdSchema.setSpareFive(DateUtils.convertToString(date1, DateUtils.YYYY_MM_DD_HH_MM_SS));
                    oContentAdSchemaService.insertOContentAdSchema(oContentAdSchema);

                } else {
                    //调用远程接口失败
                    //编辑表单
                    // 当前环节，包括流程的环节，有结束、终止等
                    oContentAdSchema.setActName("结束");
                    //流采用标准编码 flowType 01待提交 02待审核 03待发布 04发布失败 05结束 06失败结束
                    oContentAdSchema.setFlowType("06");
                    oContentAdSchema.setSpareFive(DateUtils.convertToString(date1, DateUtils.YYYY_MM_DD_HH_MM_SS));
                    oContentAdSchemaService.insertOContentAdSchema(oContentAdSchema);

                }

                /**
                 * 结果表信息
                 */
                if (StringUtils.isNotBlank(newId)) {
                    OContentAd oContentAdCondition = new OContentAd();
                    oContentAdCondition.setNewId(newId);
                    List<OContentAd> oContentAdServiceList = oContentAdService.selectOContentAdList(oContentAdCondition);
                    if (oContentAdServiceList.size() > 0 && null != oContentAdServiceList.get(0)) {
                        OContentAd oContentAd = oContentAdServiceList.get(0);
                        oContentAd.setAppNo(null);
                        oContentAd.setSpareThree(null);
                        if ("1".equals(resultCode) || 1 == resultCode) {
                            // 发布状态,advIssueState,1	已上架 2	已下架
                            oContentAd.setAdState("2");
                            oContentAd.setRemarks("广告下架成功");
                        } else {
                            // 发布状态,advIssueState,1	已上架 2	已下架
                            oContentAd.setAdState("1");
                            oContentAd.setRemarks("远程广告接口调用失败，下架失败");
                        }
                        oContentAd.setSpareFour(oContentAdSchema.getServiceType());
                        oContentAdService.insertOContentAd(oContentAd);
                    } else {
                        OContentAd oContentAd2 = new OContentAd();
                        BeanUtils.copyProperties(oContentAdSchema, oContentAd2);
                        oContentAd2.setAppNo(null);
                        oContentAd2.setSpareThree(null);
                        if ("1".equals(resultCode) || 1 == resultCode) {
                            // 发布状态,advIssueState,1	已上架 2	已下架
                            oContentAd2.setAdState("2");
                            oContentAd2.setRemarks("广告下架成功");
                        } else {
                            // 发布状态,advIssueState,1	已上架 2	已下架
                            oContentAd2.setAdState("1");
                            oContentAd2.setRemarks("远程广告接口调用失败，下架失败");
                        }
                        oContentAd2.setSpareFive(null);
                        oContentAd2.setId(null);
                        oContentAd2.setCreateBy(null);
                        oContentAd2.setCreateDate(null);
                        oContentAd2.setUpdateBy(null);
                        oContentAd2.setUpdateDate(null);
                        oContentAd2.setDelFlag("0");
                        oContentAd2.setSpareFour(oContentAdSchema.getServiceType());
                        oContentAdService.insertOContentAd(oContentAd2);
                    }
                }
            }
        }
        return AjaxResult.success("广告流程审核成功!");
    }


    /**
     * 获取广告管理维护方案详细信息
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAdSchema:query")
    @GetMapping(value = "/updateStatus")
    public AjaxResult updateStatus() {
        oContentAdSchemaService.updateStatus();
        return AjaxResult.success();
    }

}
